/** @jsxImportSource @emotion/react */
import {jsx, css } from "@emotion/react";
import * as React from "react";
import {
    Navbar,
    Toolbar,
    Text,
    Button,
    IconButton,
    MenuList,
    MenuItem,
    useTheme,
    useToast,
    LayerLoading,
    Container,
    IconMoreVertical,
    IconArrowLeft,
    IconArrowRight,
    Select,
    Spinner,
    IconRefButton,
    IconPackage,
    Touchable,
    TwoHalfRightPanel,
    VerticalMenu, DdMenuItem
} from "customize-easy-ui-component";
//import {  useDispatchIspMen,  useReport } from "../db";
//import {Helmet} from "react-helmet";
//import { Link as RouterLink,  Route, Switch } from "wouter";
import { ContainLine, TransparentInput } from "../../comp/base";
//import { useCommitOriginalData, useQueryOriginalRecord } from "../../report/db";
//import { useNewReport } from "./db";
import { Link as RouterLink } from "../../routing/Link";
import useBuildTaskMutation from "../../task/useBuildTaskMutation";
import useNewReportMutation from "./useNewReportMutation";
import {升降机 as LifterComp} from "../../device/edit/升降机";
import {FlowReportConfig} from "./FlowReportConfig";
import {getReportModelTypes} from "./reportTypeMap";

interface AddReportProps {
  defaultTitle?: string;
  readOnly?: boolean;
  editable?: boolean;
  routeData: any;
}

export const AddReport: React.FunctionComponent<AddReportProps> = props => {
  const theme = useTheme();
  //const toast = useToast();
  const detId= props.routeData.params.ispId;
  const [editing, setEditing] = React.useState(!props.readOnly);
  console.log("AddReport进入 detid=", detId, props.routeData);
  /*const [content, ] = React.useState(() => {
    return defaultDescription
      ? ''
      : null;
  });*/
  //const [image, ] = React.useState(defaultImage);
  const [title, setTitle] = React.useState(props.defaultTitle);
  //const [credit, ] = React.useState(defaultCredit);
  let filtercomp={
    id: 2,
  };
 // const { loading, items:rep , } = useReport(filtercomp);

  return (
      <TwoHalfRightPanel
          title={ `检验号 ${detId} 添加报告`
          }
          back={
              <RouterLink href={`/inspect/${detId}`}>
                  <IconButton  noBind  icon={<IconArrowLeft />}
                               variant="ghost"
                               label="后退"
                               size="md"
                               css={{
                                   marginRight: theme.spaces.sm,
                                   [theme.mediaQueries.md]: {
                                       display: "none"
                                   }
                               }}
                  />
              </RouterLink>
          }
          menu={
              <VerticalMenu>
                  <DdMenuItem label="编辑" onClick={(e) => {
                      setEditing(true);
                  }}/>
                  <DdMenuItem label="删除" onClick={(e) => {
                  }}/>
              </VerticalMenu>
          }
          divStyle={{
              margin: `${theme.spaces.sm} ${theme.spaces.sm}`
          }}
      >

          <div
              css={{
                  width:'100%',
              }}
          >
              <NewReportSelectParam id={detId} />
              <Button  size="lg" noBind
                  intent="primary"
                  iconAfter={<IconArrowRight />}
              >
               其他功能
              </Button>
          </div>

      </TwoHalfRightPanel>
  );
};

interface NewReportSelectParamProps {
    id: string;
}
const NewReportSelectParam= ( { id }: NewReportSelectParamProps
) => {
  const theme = useTheme();
  const toast = useToast();
  //模板的类型标识;
  //Todo: 获取后端的列表？ 或者，前后端同步数据维护。
  //const [tplType, setTplType] = React.useState('EL-DJ');
/*  const {result, submit:doReportBuild, loading} = useNewReport({
    isp: id, type:ingredients.modeltype , version:ingredients.modelversion
  });*/
    const {call:makeNewReport,doing,result, called, reset}= useNewReportMutation();
    const [master, setMaster] = React.useState<any>();         //就是报告校核人
    const [ispMens, setIspMens] = React.useState<any>();         //多个 检验人员[User];
    const [reviewer, setReviewer] = React.useState<any>();    //审核人
    const [approver, setApprover] = React.useState<any>();    //审批人
    const [modeltype, setModeltype] = React.useState<any>( 'EL-DJ' );
    const [modelversion, setModelversion] = React.useState<any>( '1' );
    //会有多次的render经过这里，每一回都会要求执行里面的计算啊， 【提高性能考虑】改成useMemo保存;
    const models =React.useMemo(() => getReportModelTypes('41','413','','REGUL',true), []);

  return <React.Fragment>
    <div>
      <Text variant="h6">分项报告不需要选择审批人,还没有主报告的默认添加为主报告</Text>
      <Text variant="h5">为该份报告做选择</Text>
        <FlowReportConfig  master={master} ispMens={ispMens} reviewer={reviewer} approver={approver} modeltype={modeltype} modelversion={modelversion}
                           setMaster={setMaster} setIspMens={setIspMens} setReviewer={setReviewer} setApprover={setApprover} setModeltype={setModeltype}
                           setModelversion={setModelversion} models={models}
        />

      <Button
        css={{ marginTop: theme.spaces.md }}
        size="lg"  intent={'warning'}
        disabled ={doing}
        onPress={() =>{
            let ispMids =ispMens?.map((item: any)=>{
                return item?.id;
            });
            makeNewReport(id,  master?.id,ispMids??[],
                            reviewer?.id, approver?.id, modeltype, modelversion);
        } }
      >为Isp添加新报告(主/分项)
      </Button>
      <Spinner doing={doing}/>
      { result &&
      <Text variant="h5">生成返回结果：报告ID {result.newReport.id}; 报告编号 {result.newReport?.isp?.no}; 日期：{result.newReport.upLoadDate}</Text>
      }
    </div>
    <Text>这里生成返回报告编号还无法和旧平台对接，待完善；报告编号给对外对接识别用的，内部使用报告ID</Text><br/>
      <RouterLink href={`/report/EL-DJ/ver/1/preview/${result?.newReport.id}`}>
        <Button
          size="lg" noBind
          intent="primary"
          iconAfter={<IconArrowRight />}
        >
         进入报告编制
        </Button>
      </RouterLink>
  </React.Fragment>;
};


export default AddReport;
